package com.trainoo.mina.codec;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

import java.nio.charset.Charset;

/**
 * @Auther: zt
 * @Date: 2020/4/14 16:08
 * @Description:
 */
public class MessageEncoder extends ProtocolEncoderAdapter {

    private final Charset charset;

    public MessageEncoder() {
        this.charset = Charset.defaultCharset();
    }

    // 构造方法注入编码格式
    public MessageEncoder(Charset charset) {
        this.charset = charset;
    }

    @Override
    public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
        // 转为自定义协议包
        MessagePack customPack = (MessagePack) message;
        // 初始化缓冲区
        IoBuffer buffer = IoBuffer.allocate(customPack.getLen())
                .setAutoExpand(true);
        // 设置长度、报头、内容
        buffer.putInt(customPack.getLen());
        if (customPack.getContent() != null) {
            buffer.put(customPack.getContent().getBytes());
        }
        // 重置mask，发送buffer
        buffer.flip();
        out.write(buffer);
    }
}
